package world

import (
	"context"
	"github.com/tianjigames/fairy/constants"
	"github.com/tianjigames/fairy/manager"
	"github.com/tianjigames/fairy/protos"
	"github.com/topfreegames/pitaya"
	"github.com/topfreegames/pitaya/component"
	constants2 "github.com/topfreegames/pitaya/constants"
	"github.com/topfreegames/pitaya/logger"
)

type GameHandler struct {
	component.Base
}

func NewGameHandler() *GameHandler {
	return &GameHandler{}
}

func (p *GameHandler) PlayerAuth(ctx context.Context,req *protos.GWPlayerAuth) (*protos.WGPlayerAuthRet,error) {
	maxConnectNum := pitaya.GetConfig().GetInt(constants2.WorldServerMaxpoolPlayerSize)

	//获取在游戏服务器上的人数
	reply := &protos.PWOnGameServerPlayerNumRet{}
	err := pitaya.RPC(ctx,constants.WPOnGameServerPlayerNumRoute,reply,&protos.WPOnGameServerPlayerNum{})
	if err != nil {
		logger.Log.Errorf("[HallHandler] CheckLoginNum failed,error:%s",err.Error())
		return nil,err
	}

	onlineCount := int(reply.Num)
	if onlineCount >= maxConnectNum {
		return &protos.WGPlayerAuthRet{
			RetCode:    constants.PlayerPoolFull,
		},nil
	}

	playerInfo := manager.GameServerPlayerManager.GetPlayerInfoByAccount(req.AccountId,req.AppId)
	if playerInfo == nil {
		return &protos.WGPlayerAuthRet{
			RetCode:    constants.PlayereUnloginError,
		},nil
	}

	if req.Ticket != playerInfo.Ticket {
		return &protos.WGPlayerAuthRet{
			RetCode:    constants.PlayerTicketError,
		},nil
	}

	if playerInfo.FullData == nil {
		return &protos.WGPlayerAuthRet{
			RetCode:    constants.PlayerNoDataError,
		},nil
	}


	playerInfo.ServerId = req.ServerId
	manager.GameServerPlayerManager.SetPlayerOnline(req.AccountId,req.AppId)
	if playerInfo.GangId > 0 {
		//todo:通知战队玩家上线
	}

	ret := &protos.WGPlayerAuthRet{
		PlayerData: playerInfo.FullData,
		RetCode:    constants.InitGameAuthSuccess,
	}
	playerInfo.FullData = nil
	return ret,nil
}

/**
强制玩家下线
 */
func (p *GameHandler) ForceLogout(req *protos.GWRetForceLogout) (*protos.WGRetForceLogoutrRet,error) {
	if req.GetAccountId() > 0 {
		playerInfo := manager.GameServerPlayerManager.GetPlayerInfoByAccount(req.AccountId,req.AppId)
		if playerInfo != nil {
			if req.GetReason() == constants.WorldKickUserSend {

			}else if req.GetReason() == constants.WorldKickUserOffline {//玩家掉下后 清除在线数据
				playerInfo.FullData = nil
				manager.GameServerPlayerManager.SetPlayerOffline(req.AccountId,req.AppId)
			}
		}
	}

	return nil,constants2.ErrReturnNil
}
